import { reactive, ref, nextTick } from 'vue'
import type { MsgData } from '@/types/userInfo'
import type { PageParams } from '@/types/common'
import { getUnreadMessage } from '@/api/user'
import { useUserInfoStore } from '@/stores'
import { ImageAddHttp, formatTimestamp } from '@/utils/index'
import { onLoad } from '@dcloudio/uni-app'

export function useScript() {
  const dataList = ref<MsgData[]>([])
  const isLoad = ref(false)
  const userInfo = ref(useUserInfoStore().profile)
  const pagination = reactive<PageParams>({
    pageSize: 8,
    page: 1,
    total: 0,
    order: 'desc',
  })

  async function getMeg() {
    const params = {
      page: pagination.page,
      limit: pagination.pageSize,
      order: 'desc',
    }
    isLoad.value = true
    const resultList = await getUnreadMessage(params)

    if (resultList.code) {
      // 新添加进 dataList中
      resultList.data.list.forEach((item: any) => {
        dataList.value.push({
          id: item.id,
          user_id: item.user_id,
          avatar: ImageAddHttp(item.avatar),
          nickname: item.nickname,
          username: `@${item.username}`,
          createtime: formatTimestamp(item.createtime, 'yyyy-MM-dd HH:mm:ss'),
          content: item.content,
          is_liked: false,
          is_collected: false,
        })
      })
      console.log(dataList.value)
      // 更新总数
      pagination.total = resultList.data.total
      pagination.page = resultList.data.currentPage
    }
    isLoad.value = false
  }

  async function loadMoreComments() {
    if (isLoad.value) return
    if (
      pagination.page !== undefined &&
      pagination.page < Math.ceil((pagination.total ?? 0) / (pagination.pageSize ?? 1))
    ) {
      pagination!.page++
      await getMeg()
    }
  }

  async function refreshComments() {
    if (isLoad.value) return
    dataList.value.length = 0
    pagination.page = 1
    await getMeg()
  }

  async function Back() {
    uni.redirectTo({
      url: '/pages/profile/profile',
    })
  }

  async function gotoUserInfo(id: number) {
    uni.navigateTo({
      url: `/pages/profile/profile?id=${id}`,
    })
  }

  onLoad(async () => {
    await nextTick()
    await refreshComments()
  })

  return {
    userInfo,
    dataList,
    gotoUserInfo,
    loadMoreComments,
    refreshComments,
    confirm,
    Back,
  }
}
